// 引入model
const { adminModel } = require('./model/admin');
const { bannerModel } = require('./model/banner');
const { blogModel } = require('./model/blog');
const { blogTypeModel } = require('./model/blogType');

/**
 * joi外键校验
 * @param {*} modelName 外键关联主键的模型名称
 * @returns
 */
exports.validateForeignKey = (modelName) => async (value, helpers) => {
	let handlerModule = getModel(modelName);
	if (!handlerModule) return helpers.error(`${modelName}表不存在`, { value });
	if (!value) return; // 业务中允许不传这个外键，说明是编辑，可以跳过验证
	const record = await handlerModule.findByPk(value);
	if (!record) {
		return helpers.error(`any.invalid`, { value });
	}
	return value;
};

function getModel(name) {
	switch (name) {
		case 'admin':
			return adminModel;
			break;
		case 'banner':
			return bannerModel;
			break;
		case 'blog':
			return blogModel;
			break;
		case 'blogType':
			return blogTypeModel;
			break;
		default:
			return false;
	}
}
